#include "serialport.h"

void SerialWorker::HandleSerialData(QByteArray data)     //qint8 send_buf_flag)
{
    // 在这里可以进行串口数据处理操作
    // 处理完成后通过信号将结果发送给主线程

//    qDebug() << "#### thread recv" << processedData.toHex(' ');
//    qDebug() << "[Thread] get flag:" << send_buf_flag;
//    m_handle(data, send_buf_flag);

    //取出第三第四位的命令位
    const QByteArray searchBytes = QByteArray::fromHex("2001");
    const QByteArray cmd = data.mid(2,2);
    if(cmd == searchBytes)
    {
         qDebug() << "cus";
         cus_handle(data);
    }
    else
    {
        qDebug() << "default";
        default_handle(cmd, data);

    }

}

qint16 SerialWorker::fsl_U8_to_U16(char front, char back)
{
    qint16 data = 0;
    qint8 *temp = (qint8 *)(&data);
    *temp = front;
    temp++;
    *temp = back;

    return data;

}

string SerialWorker::fsl_hexArrayToAsciiString(unsigned char arr[], int len)
{
    stringstream ss;

    for (int i = 0; i < len; i++) {
        int n = (int)arr[i];
        char c = isprint(n) ? (char)n : '.'; // 判断是否为可打印字符
        ss << c;      // 将字符追加到字符串中
    }

    return ss.str();
}

QString SerialWorker::byteArrayToHexString(const QByteArray& data) {
     QByteArray hexArray = data.toHex(); // 将QByteArray转换为十六进制字符串
     QByteArray asciiArray = QByteArray::fromHex(hexArray); // 将十六进制字符串转换为QByteArray
     QString asciiString = QString::fromUtf8(asciiArray.constData(), asciiArray.length()); // 将QByteArray转换为QString
     return asciiString;
}

qint16 SerialWorker::byteArrayToQint16(const QByteArray& data) {
    // 要存放合并后的16位整数的变量
    qint16 value = 0;

    // 将第一个字节向左移动8位，然后与第二个字节进行按位或运算
    value |= (data.at(0) << 8);
    value |= data.at(1);

    return value;
}


void SerialWorker::fsl_handle_query_device_nodes(QByteArray data)
{
    //根据协议，第8、9位代表在线节点数量
    fsl_query_all_node_num = fsl_U8_to_U16(data.at(8), data.at(9));
    //初始化数组下标
    array_pos = 0;
    //sta设备数量清零
    sta_device_count = 0;
//    //根据节点数量开辟数组
//    if(NULL == cco_device_info)
//    {
//        cco_device_info = new device_info[fsl_query_all_node_num];
//    }
//    else
//    {
//        delete[] cco_device_info;
//        cco_device_info = new device_info[fsl_query_all_node_num];
//    }
}

void SerialWorker::fsl_handle_query_device_info(QByteArray data)
{
    //根据协议，第9位开始的连续6个字节，就是mac地址, 所以前8位要扔掉
    qint8 offset = 8;
    qint16 len = 6;
    //取出该设备的MAC地址
    cco_device_info.mac_address = data.mid(offset, len);
//    qDebug() << " 1111111111111111" << cco_device_info[array_pos].mac_address;
    //取出该设备的Dev addr（单地址）
    offset =  22;
    len = 2;
    cco_device_info.dev_address = data.mid(offset, len);
    //取出设备信息的字符串
    offset = 28;
    len = fsl_U8_to_U16(data.at(26), data.at(27));
    QByteArray dev_info_string = data.mid(offset, len);
    cco_device_info.string_dev_info = byteArrayToHexString(dev_info_string);
    //判断此设备是cco还是sta
    cco_device_info.dev_type = cco_device_info.string_dev_info.contains("cco");
}

void SerialWorker::fsl_handle_query_device_property_result(QByteArray data, STA_Device *sta_device_property_array, qint16 array_pos)
{
    qint16 index = 0;
    //根据协议，第9位开始的连续6个字节，就是mac地址, 所以前8位要扔掉
    qint16 offset = 8;
    qint16 len = 6;
    //取出该设备的MAC地址
    sta_device_property_array[array_pos].mac_address = data.mid(offset, len);
    qDebug() <<"mac: "<< sta_device_property_array[array_pos].mac_address.toHex(' ');
    //取出该设备的Dev addr（单地址）
    offset =  22;
    len = 2;
    sta_device_property_array[array_pos].dev_address = data.mid(offset, len);
    qDebug() <<"dev: "<< sta_device_property_array[array_pos].dev_address.toHex(' ');


    /* 获取开关状态 */
    if(data.contains(QByteArray::fromHex("01000100")))
    {
        index = data.indexOf(QByteArray::fromHex("01000100"));//返回第一个出现该字符串的数组下标
        sta_device_property_array[array_pos].light_switch = data.at(index + 8);
//        qDebug() << "on/off: " << sta_device_property_array[array_pos].light_switch;
    }
    /* 获取灯的亮度 min:0   max:10000   步长:1  */
    if(data.contains(QByteArray::fromHex("01000400")))
    {
        index = data.indexOf(QByteArray::fromHex("01000400"));//0-1w两个字节就可以表示
        offset = index + 8;
        len = fsl_U8_to_U16(data.at(index + 6), data.at(index + 7));
        sta_device_property_array[array_pos].brightness = data.mid(offset, len);

//        qDebug() << "brightness: " << sta_device_property_array[array_pos].brightness.toHex(' ');
    }
    /* 获取灯的警报信息 bit0-灯具故障   bit1-倾斜  bit2-过温  bit3-漏电  bit4-过载
                                    bit5-过压   bit6-欠压   bit7-过流 */
    if(data.contains(QByteArray::fromHex("02000E00")))
    {
        index = data.indexOf(QByteArray::fromHex("02000E00"));//1个字节就可以表示
        sta_device_property_array[array_pos].warning_value.append(data.at(index + 8));
//        qDebug() << "warning: " << sta_device_property_array[array_pos].warning_value.toHex(' ');
    }

    /* 倾斜角度  min:0  max:90  步长:1 */
    if(data.contains(QByteArray::fromHex("0D000E00")))
    {
        index = data.indexOf(QByteArray::fromHex("0D000E00"));//1个字节就可以表示
        offset = index + 8;
        len = fsl_U8_to_U16(data.at(index + 6), data.at(index + 7));
        sta_device_property_array[array_pos].qingxie_value = data.mid(offset, len);

//        qDebug() << "tilt: " << sta_device_property_array[array_pos].qingxie_value.toHex(' ');
    }

    /*  温度  min:-400   max:850   步长:1   单位:0.1℃  */
    if(data.contains(QByteArray::fromHex("11000E00")))
    {
        index = data.indexOf(QByteArray::fromHex("11000E00"));//4个字节就可以表示
        offset = index + 8;
        len = fsl_U8_to_U16(data.at(index + 6), data.at(index + 7));
        sta_device_property_array[array_pos].temperature_value = data.mid(offset, len);

//        qDebug() << "temperature: " << sta_device_property_array[array_pos].temperature_value.toHex(' ');
    }

    /* 功率    min:0    max:1000000     步长:1    单位:1mW   */
    if(data.contains(QByteArray::fromHex("18000E00")))
    {
        index = data.indexOf(QByteArray::fromHex("18000E00"));//4个字节就可以表示
        offset = index + 8;
        len = fsl_U8_to_U16(data.at(index + 6), data.at(index + 7));
        sta_device_property_array[array_pos].power_value = data.mid(offset, len);

//        qDebug() << "power: " << sta_device_property_array[array_pos].power_value.toHex(' ');
    }

    /* 电压   min:0   max:4000  步长:1   单位:100mV*/
    if(data.contains(QByteArray::fromHex("01100E00")))
    {
        index = data.indexOf(QByteArray::fromHex("01100E00"));//2个字节就可以表示
        offset = index + 8;
        len = fsl_U8_to_U16(data.at(index + 6), data.at(index + 7));
        sta_device_property_array[array_pos].voltage_value = data.mid(offset, len);
//        qDebug() << "voltage_value: " << sta_device_property_array[array_pos].voltage_value.toHex(' ');
    }

    /* 电流  min:0    max:100000   步长:1    单位:1mA*/
    if(data.contains(QByteArray::fromHex("02100E00")))
    {
        index = data.indexOf(QByteArray::fromHex("02100E00"));//3个字节就可以表示
        offset = index + 8;
        len = fsl_U8_to_U16(data.at(index + 6), data.at(index + 7));
        sta_device_property_array[array_pos].electricity_value = data.mid(offset, len);

//        qDebug() << "electricity_value: " << sta_device_property_array[array_pos].electricity_value.toHex(' ');
    }

    /* 漏电流    min:0   max:100   步长:1   单位:1mA */
    if(data.contains(QByteArray::fromHex("03100E00")))
    {
        index = data.indexOf(QByteArray::fromHex("03100E00"));//1个字节就可以表示
        offset = index + 8;
        len = fsl_U8_to_U16(data.at(index + 6), data.at(index + 7));
        sta_device_property_array[array_pos].leak_current_value = data.mid(offset, len);

//        qDebug() << "leak_current_value: " << sta_device_property_array[array_pos].leak_current_value.toHex(' ');
    }

    /* 功率因素 min:0 max:100 步长:1 */
    if(data.contains(QByteArray::fromHex("04100E00")))
    {
        index = data.indexOf(QByteArray::fromHex("04100E00"));//1个字节就可以表示
        offset = index + 8;
        len = fsl_U8_to_U16(data.at(index + 6), data.at(index + 7));
        sta_device_property_array[array_pos].power_factor_value = data.mid(offset, len);

//        qDebug() << "power_factor_value: " << sta_device_property_array[array_pos].power_factor_value.toHex(' ');
    }

    /* 电量   min:0   max:4294967295   步长:1   单位:0.0001 度*/
    if(data.contains(QByteArray::fromHex("05100E00")))
    {
        index = data.indexOf(QByteArray::fromHex("05100E00"));//4个字节就可以表示
        offset = index + 8;
        len = fsl_U8_to_U16(data.at(index + 6), data.at(index + 7));
        sta_device_property_array[array_pos].electric_quantity_value = data.mid(offset, len);

//        qDebug() << "electric_quantity_value: " << sta_device_property_array[array_pos].electric_quantity_value.toHex(' ');
    }

    /* 运行时间   min:0     max:4294967295    步长:1    单位:S */
    if(data.contains(QByteArray::fromHex("06100E00")))
    {
        index = data.indexOf(QByteArray::fromHex("06100E00"));//4个字节就可以表示
        offset = index + 8;
        len = fsl_U8_to_U16(data.at(index + 6), data.at(index + 7));
        sta_device_property_array[array_pos].run_time_value = data.mid(offset, len);

//        qDebug() << "run_time: " << sta_device_property_array[array_pos].run_time_value.toHex(' ');
    }
}


void SerialWorker::fsl_handle_query_device_property(QByteArray data)
{
    if(data.contains(cco_device_info.mac_address))
    {
        qDebug() << "[DEBUG]I am CCO";
        send_cmd_flag = fsl_send_cmd_free;
        return;
    }
    else
    {
        qDebug() << "[DEBUG]I am STA";

        if(sta_device_count < fsl_query_all_node_num)
            sta_device_count++;
        if(NULL == sta_device_property_array)
        {
            sta_device_property_array = new STA_Device[sta_device_count];
                                                                            /* 操作对应数组下标，所以要-1 */
            fsl_handle_query_device_property_result(data, sta_device_property_array, sta_device_count-1);
        }
        else
        {
            STA_Device *newArray = new STA_Device[sta_device_count];
            for(qint16 i = 0; i < sta_device_count - 1; i++)        //-1是为了防止旧数组越界，并且保持新数组最后一位是空数据状态
            {
                newArray[i] = sta_device_property_array[i];
            }

            delete[] sta_device_property_array;
            sta_device_property_array = newArray;
            fsl_handle_query_device_property_result(data, sta_device_property_array, sta_device_count-1);
        }
    }

}


void SerialWorker::cus_handle(QByteArray data)
{
    //判断func_code
    switch (data.at(20)) {
        case fsl_recv_cco_cus_query_device_info_func_code:
        {
            fsl_handle_query_device_info(data);
            send_cmd_flag = fsl_sned_cmd_query_device_info_flag;
            emit newDataReady(send_cmd_flag);
        }
        break;
        case fsl_recv_cco_cus_query_device_property_func_code:
        {
            fsl_handle_query_device_property(data);
            /* sta设备属性搜集完毕 */
            if(sta_device_count == fsl_query_all_node_num - 1)
            {
                send_cmd_flag = fsl_sned_cmd_query_device_property_flag;
                emit newDataReady(send_cmd_flag);
            }
        }
        break;
        default:
            return;
    }

}

void SerialWorker::default_handle(QByteArray cmd, QByteArray data)
{
    //判断默认cmd类型
    switch(byteArrayToQint16(cmd))
    {
        case fsl_recv_default_common_Query_device_nodes:
        {
            fsl_handle_query_device_nodes(data);
            send_cmd_flag = fsl_sned_cmd_query_device_nodes_flag;
        }
        break;
        default:
            return;

    }
    emit newDataReady(send_cmd_flag);


}

